<?php 
/**
 +------------------------------------------------------------------------------
 * b2b购物车操作类
 +------------------------------------------------------------------------------
 * @category   SubAction
 * @package  app
 +------------------------------------------------------------------------------
 */
class CartB2B {
	// 错误信息行数
	protected $line='';
	// 购物车模型
	private $mode='cart_o2o';
	// 购物车模型类
	private $dao;
	// 购物车字段
	private $field = 'id,user_id,session_id,site_id,product_id,product_thumb,product_name,product_psn,price,priceall,number,ctime,status';
	// 用户ID
	private $user_id;
	// session id
	private $sessionid;
	
	function __construct($user_id=0,$sessionid='',$mode=''){
		$this->mode = $mode ? $mode : $this->mode;
		$this->dao 		 = M($this->mode);
		$this->user_id   = $user_id ? $user_id : 0;
		if ( $sessionid ) $this->sessionid = $sessionid;
	}
	
	/**
	 * 返回购物车内的商品信息
	 * @param array $map         查询条件
	 * @param array $statistics  是否统计
	 * @param array $siteinfo    是否需要店铺信息
	 * @return array
	 */
	function cart_product($map=array(),$statistics=false,$siteinfo=true) {
		$this->line='cart::'.__LINE__;
		$map_tmp = array();
		$map_tmp['status']  = array('in','1,3');
		$map_tmp['user_id'] = $this->user_id;
		if ( $this->sessionid ) $map_tmp['session_id'] = $this->sessionid;
		$map = $map ? array_merge($map_tmp, $map) : $map_tmp;
		if ( $map['user_id'] ) unset($map['session_id']);
		
		$content = $this->dao->field( $this->field )->where($map)->select();
		if ( $statistics ) {
			$cons1 = $this->dao->field( ' SUM(`number`) AS pnum ' )->where($map)->find();
			$map['status']  = 1;
			$cons2 = $this->dao->field( ' SUM(`priceall`) AS ptotal ' )->where($map)->find();
			$cons = array_merge($cons1,$cons2);
			$content['statistics'] = $cons;
		}
		
		return $content;
	}//end cart_product

	function is_minsale($cartid,$num){
		$re = $this->dao->field('product_id')->where(array('id'=>$cartid))->find();
		$m = M('product_price_b2b');
		$re =$m->field('minsale')->where(array('product_id'=>$re['product_id']))->find();
		//dump($m->getLastSql());
		return ($re['minsale']<$num) ? $num : $re['minsale']; 
	}
	
	/**
	 * 添加商品到购物车
	 * @param array $product  需要加入购物车的产品
	 * @return int
	 */
	function add($product,$num=1) {
		$this->line = 'add_cart::'.__LINE__;
		if ( ! $product || ! is_array($product) ) return false;
		$map = array(
				'product_id' => $product['des']['product_id'],
				'site_id'    => $product['site_id'],
				'user_id'    => $this->user_id,
				'session_id' => $this->sessionid
		);
		$product_cart = $this->cart_product( $map );
		$map['status'] = 2;
		$this->clear_cart($map);
		if ( $product_cart ) {// 购物车内已存在
			$nonum = $num + $product[0]['number'];
			$num = self::is_minsale($product['des']['product_id'], $nonum);
			$id = $product[0]['id'];
			$mode = M('');
			$re = $mode->query( "update {$this->mode} set `price`={$product['price']}, `number`={$num}, `priceall`=".$product['price']*($product_cart[0]['number']+$num).
				" where product_id={$product['des']['product_id']} and  user_id={$this->user_id} and site_id={$product['site_id']} and session_id='". $this->sessionid."'" );
			
		} else {// 新加入商品
			$product_input = array(
					'user_id'       => $this->user_id,
					'session_id'    => $this->sessionid,
					'site_id'       => $product['site_id'],
					'product_id'    => $product['des']['product_id'],
					'product_thumb' => $product['image'],
					'product_name'  => $product['des']['name'],
					'product_psn'   => $product['code'],
					'price'         => $product['price'],
					'priceall'      => (int)($product['price']*$num),
					'number'        => $num,
					'ctime'         => time(),
					'status'        => '1',
			);
			$re = $this->dao->add($product_input);
		}
		
		return $re;
	}//end add
	
	/**
	 * 更新购物车内的产品
	 * @param int|array $index  需要更新的记录，当值不为数组时默认为记录ID
	 * @param array     $data	更新数据,数组键为字段名，值为要更新的数据
	 * @return array
	 */
	function update($index,$data) {
		$this->line='update::'.__LINE__;
		if ( ! is_array($index) )
			$re = $this->dao->where( array('id'=>array('in',$index)) )->save($data);
		else
			$re = $this->dao->where( $index )->save($data);
		//echo $this->dao->getLastSql();
		return $re;
	}//end update
	
	 /**
	  * 清空（删除）购物车
	  * @param array $map  查询条件
	  * @return array
	  */
	 function clear_cart($map) {
	 	$this->line='clear_cart::'.__LINE__;
	 	$re = $this->dao->where($map)->delete();
	 	return $re;
	 }//end clear_cart

	 /**
	  * 修改购物车商品数量
	  * @param array $id  商品ID
	  * @param array $num 商品数量
	  * @return array
	  */
	 function update_num($id,$num) {
	 	$this->line='update_num::'.__LINE__;
	 	$m = M('');
	 	$num=self::is_minsale($id,$num);
	 	//die($num);
	 	$query = "update {$this->mode} set number={$num}, priceall=price*{$num} where id={$id}";
	 	$re = $m->query( $query );
	 	return $re;
	 }//end update_num
	 
	 /**
	  * 登录前登录后购物车产品合并
	  */
	 function merge() {
	 	$this->line='sidtouserid::'.__LINE__;
	 	if ( ! $this->user_id ) return false;
	 	$content1 = $this->dao->where( array('user_id'=>$this->user_id) )->select();
	 	$content2 = $this->dao->where( array('user_id'=>0,'session_id'=>$this->sessionid) )->select();// 上次登录时的购物车记录
	 	// 产品叠加
	 	if ( $content2 ) {
	 		foreach ( $content2 as $key=>&$value ) {
	 			foreach ( $content1 as &$val ) {
	 				// 合并去除重复产品
	 				if ( ($val['product_id']==$value['product_id']) && ($val['site_id']==$value['site_id']) ) {
	 					$value['number']   += $val['number'];
	 					$value['priceall'] += $val['number'] * $val['price'];
	 					$this->clear_cart( array('id'=>$val['id']) );
	 					unset($val);
	 				}
	 			}
	 			$value['user_id'] = $this->user_id;
	 			$this->dao->save( $value );
	 		}
	 	}
	 	if ( $content1 ) {
	 		$ids = '0';
	 		foreach ( $content1 as $value ) {
	 			$ids .= ','.$value['id']; 
	 		}
	 		$this->dao->where( array('id'=>array('in'=>$ids)) )->save( array('session_id'=>$this->sessionid) );
	 	}
	 }//end merge
	 
	 /**
	  * 二维数组返回一维或字符串
	  * @param array  $_arr
	  * @param string $_field
	  * @param string $_type 1为数组 2为字符串
	  * @return array|string
	  */
	 function checkout_price(){
	 	$products = self::cart_product();
	 	$model = M('ProductPriceB2b');
	 	foreach ( $products as $product) {
	 		$restu = M('product')->field( 'status' )->find($product['product_id']);
	 		if ( $restu['status'] != 1 ) {
	 			$this->dao->delete( $product['id'] );
	 			continue;
	 		}
	 		$field = 'price,jiayi,jiaer,jiasan,jiasi';
	 		$info = $model->field($field)->where(array('product_id'=>$product['product_id']))->find();
	 		$price = role_price($_SESSION['role'],$info);
	 		$price = $price/100;
	 		
	 		//$map = array( 'id'=>$product['id'],'' );
	 		$query = "update cart_b2b set price={$price},priceall=price*number where id={$product['id']}";
	 		M()->query($query);
	 	}
	 }
	 
	 /**
	  * 二维数组返回一维或字符串
	  * @param array  $_arr
	  * @param string $_field
	  * @param string $_type 1为数组 2为字符串
	  * @return array|string
	  */
	 function arr2to1($_arr,$_field = '0',$_type = '1'){
	 	if ( ! $_arr ) return array();
	 	$arrayids = array();
	 	foreach ($_arr as $k => $v){
	 		$arrayids[$k] = $v[$_field];
	 	}
	 	if($_type != '1') $arrayids = implode(',',$arrayids);
	 
	 	return $arrayids;
	 }
	 
}
